package com.microstation.controller.front;

import com.alibaba.fastjson.JSONArray;
import com.microstation.common.AppConst;
import com.microstation.common.Result;
import com.microstation.controller.system.BaseController;
import com.microstation.entity.po.QuestionnaireRec;
import com.microstation.entity.po.UserInfo;
import com.microstation.enums.ResultEnum;
import com.microstation.service.QuestionnaireRecService;
import com.microstation.service.UserInfoService;
import com.microstation.util.CookieUtil;
import com.microstation.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping(value = "/api/questionnaire")
public class QuestionnaireController extends BaseController {
    private final static Logger LOG = LoggerFactory.getLogger(QuestionnaireController.class);

    @Autowired
    private QuestionnaireRecService questionnaireRecService;
    @Autowired
    private UserInfoService userInfoService;

    @PostMapping(value = "/saveQues")
    public Result saveQues(@RequestParam(name = "quesJsonStr", defaultValue = "") String quesJsonStr, HttpServletRequest request) {
        try {
            if (StringUtil.isEmpty(quesJsonStr)) {
                return new Result(Boolean.TRUE, ResultEnum.EMPTY, AppConst.NULL);
            }
            List<QuestionnaireRec> quesList = JSONArray.parseArray(quesJsonStr, QuestionnaireRec.class);
            UserInfo userInfo = userInfoService.findOne(Long.parseLong(CookieUtil.getCookieValByName(request, AppConst.COOKIE_NAME)));
            return questionnaireRecService.saveQues(userInfo, quesList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Boolean.TRUE, ResultEnum.ERROR.getType(), e.getMessage(), AppConst.NULL);
        }
    }
}
